//
//  PlayerViewController.swift
//  MiniFilmDemo
//
//  Created by 刘青昀 on 16/10/21.
//  Copyright © 2016年 7yun. All rights reserved.
//

import UIKit
import AVFoundation
class PlayerViewController: UIViewController {
    
    @IBOutlet weak var backButton: UIButton!
    
    @IBOutlet weak var finishView: UIView!
    
    @IBOutlet weak var bottomView: UIView!
    
    @IBOutlet weak var playButton: UIButton!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var slider: UISlider!
    
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var bottom: NSLayoutConstraint!
    var playerUrl = ""
    //播放状态
    var isPlaying = true
    //是否加载成功
    var isLoadFinish = false
    
    lazy var player:AVPlayer = {
       //创建播放源
        let item = AVPlayerItem.init(URL: NSURL.init(string:self.playerUrl)!)
        //创建播放器
        let tplayer = AVPlayer.init(playerItem: item)
        //添加观察者
        item.addObserver(self, forKeyPath: "loadedTimeRanges", options: .New, context: nil)
        //获取播放结束的时刻
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayerViewController.endPlayAction), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
        return tplayer
    }()
    
override func viewDidLoad() {
        super.viewDidLoad()
    
    self.player.play()
    self.creatPlayLayer()
    self.getPlayProgress()

       
    }
    func transformTime(time:CGFloat)->String{
        //获取分
        let minute = Int(time) / 60
        var minutestr = ""
        if minute<10 {
            minutestr = "0\(minute)"
        }else{
            minutestr = "\(minute)"
        }
        //获取秒
        let second = Int(time)%60
        var secondstr = ""
        if second < 10 {
            secondstr = "0\(second)"
        }else{
            secondstr = "\(second)"
        }
        return "\(minutestr):\(secondstr)"
    }

    
}
//观察者
extension PlayerViewController{
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //获取当前播放源的总时间
        let duraction = self.player.currentItem?.duration
        _ = Float((duraction?.value)!)/Float((duraction?.timescale)!)
        //获取当前的缓存时间
        //获取播放源对象
        let item = object as! AVPlayerItem
        //获取缓存进度对象
        let value = item.loadedTimeRanges.first
        let timeRange = value?.CMTimeRangeValue
        //获取当前缓存到的时间
        let current = timeRange?.duration
        let currentTime = Float((current?.value)!)/Float((current?.timescale)!)
        if currentTime > 1{
            self.isLoadFinish = true
        }
    }
    
    
}
//播放功能相关
extension PlayerViewController{
    func endPlayAction(){
        self.playButton.setImage(UIImage.init(named: "page_play_nomal.png"), forState: .Normal)
        self.isLoadFinish = false
        self.finishView.hidden = false
    
    }
    func getPlayProgress(){
        //获取播放进度
        self.player.addPeriodicTimeObserverForInterval(CMTimeMake(1, 1), queue: dispatch_get_global_queue(0, 0)) { (currentTime) in
            //计算时间（秒）
            //当前时间
            let current = CGFloat(currentTime.value)/CGFloat(currentTime.timescale)
            let currentStr  = self.transformTime(current)
            //总的时间
            let duraction = CGFloat((self.player.currentItem?.duration.value)!)/CGFloat((self.player.currentItem?.duration.timescale)!)
            let duractionStr = self.transformTime(duraction)
            //计算进度
            let progress = current/duraction
            //回到主线程刷新数据
            dispatch_async(dispatch_get_main_queue(), { 
                self.timeLabel.text = "\(currentStr)/\(duractionStr)"
                self.slider.value = Float(progress)
            })
        }
    }
    
}
//界面相关
extension PlayerViewController{
    func creatPlayLayer(){
        let playLayer = AVPlayerLayer.init(player: self.player)
        playLayer.frame = self.view.bounds
        self.view.layer.addSublayer(playLayer)
        self.view.bringSubviewToFront(self.backButton)
        self.view.bringSubviewToFront(self.bottomView)
        self.view.bringSubviewToFront(self.finishView)
        
    }
    
}
//按钮点击
extension PlayerViewController{
    //触屏消除上下的文字或者图片
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if bottom.constant == 0{
            UIView.animateWithDuration(0.3, animations: { 
                self.bottom.constant = -50
                
                self.topConstraint.constant = -50
                self.view.layoutIfNeeded()
            })
        }else{
            UIView.animateWithDuration(0.3, animations: { 
                self.bottom.constant = 0
                self.topConstraint.constant = 10
                self.view.layoutIfNeeded()
            })
        }
    }
    //滑条
    @IBAction func sliderAction(sender: AnyObject) {
        //拿到进度值
        let progress = slider.value
        //获取总的时间
        let time = Float((self.player.currentItem?.duration.value)!) / Float((self.player.currentItem?.duration.timescale)!)
        //计算当前时间
        let current = Int64(time*progress)
        //设置进度
        self.player.seekToTime(CMTimeMake(current, 1))
    }
    
    //重新播放
    @IBAction func playAction2(sender: AnyObject) {
        self.slider.value = 0
        self.playButton.setImage(UIImage.init(named: "pauseBtn.png"), forState: .Normal)
        self.isPlaying = true
        finishView.hidden = true
        self.player.seekToTime(CMTimeMake(0, 10))
        self.player.play()
    }
    //暂停、播放
    @IBAction func playAction(sender: AnyObject) {
        if self.isPlaying{
            self.player.pause()
            self.isPlaying = false
            sender.setImage(UIImage.init(named: "page_play_normal.png"), forState: .Normal)
        }else{
            self.player.play()
            self.isPlaying = true
            sender.setImage(UIImage.init(named: "pauseBtn.png"), forState: .Normal)
        }
        
    }
    //返回
    @IBAction func backAction(sender: AnyObject) {
        self.player.pause()
        self.player.currentItem?.removeObserver(self, forKeyPath: "loadedTimeRanges")
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}
//MARK:横屏相关
extension PlayerViewController{
    override func shouldAutorotate() -> Bool {
        return true
    }
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .LandscapeRight
    }
}
